Skip to content

fix(proxy/client): redact api key from key/info client error messages - #31342

Merged
mateo-berri merged 2 commits into
litellm_internal_stagingfrom
litellm_redact_client_key_leak
Jun 26, 2026
Merged

mateo-berri merged 2 commits into
litellm_internal_stagingfrom
litellm_redact_client_key_leak

Conversation

@yucheng-berri

@yucheng-berri yucheng-berri commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Resolves LIT-4013

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all unit tests on make test-unit
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have requested a Greptile review by commenting @greptileai and received a Confidence Score of at least 4/5 before requesting a maintainer review (5/5 on the current commit)

CI (LiteLLM team)

Screenshots / Proof of Fix

KeysManagementClient.info() builds GET /key/info?key=<key>, so the raw key sits in the request URL. When the proxy returns a non-2xx, requests raises HTTPError; its string form and its chained original both carry the URL, so any caller that logs the error or lets it propagate writes the full key to its logs

Repro consumer (mirrors how a caller surfaces the error):

import logging, sys
from litellm.proxy.client.keys import KeysManagementClient

logging.basicConfig(level=logging.ERROR, format="%(levelname)s | %(message)s")
auth, lookup = sys.argv[1], (sys.argv[2] if len(sys.argv) > 2 else sys.argv[1])
client = KeysManagementClient(base_url="http://localhost:4000", api_key=auth)
try:
    client.info(key=lookup)
except Exception as e:
    logging.error(f"Error getting key info: {e}")     # str(e) surface
    # logging.exception(...) / uncaught -> traceback surface

Server side is already safe; the 404 body carries no key and the auth error masks it:

$ curl -sS "http://localhost:4000/key/info?key=sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz" -H "Authorization: Bearer sk-1234"
{"error":{"message":"Key not found in database","type":"not_found_error","param":"key","code":"404"}}

$ curl -sS "http://localhost:4000/key/info" -H "Authorization: Bearer sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz"
{"error":{"message":"Authentication Error, Invalid proxy server token passed. Received API Key = sk-...wxyz, ...","code":"401"}}

BEFORE (unfixed client). The str(e) log leaks the key, on the 404 path (valid master auth, bad lookup key) and the 401 path (bad key as credential):

$ python repro.py sk-1234 sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz
ERROR | Error getting key info: 404 Client Error: Not Found for url: http://localhost:4000/key/info?key=sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz

$ python repro.py sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz
ERROR | Error getting key info: 401 Client Error: Unauthorized for url: http://localhost:4000/key/info?key=sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz

and logging.exception() (or an uncaught error) leaks it through the rendered traceback:

$ python repro_traceback.py sk-1234 sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz
Traceback (most recent call last):
  ...
  File ".../litellm/proxy/client/keys.py", line 314, in info
    response.raise_for_status()
  ...
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://localhost:4000/key/info?key=sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz

AFTER (with this fix), both the message and the traceback scrub the query param to ?REDACTED:

$ python repro.py sk-1234 sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz
ERROR | Error getting key info: 404 Client Error: Not Found for url: http://localhost:4000/key/info?REDACTED

$ python repro_traceback.py sk-1234 sk-cdo1234567890ABCDEFghijKLMNOPqrstuvwxyz
Traceback (most recent call last):
  ...
  File ".../litellm/proxy/client/keys.py", line 322, in info
    raise requests.exceptions.HTTPError(
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: http://localhost:4000/key/info?REDACTED

The happy path is unaffected; a valid lookup still returns the key info:

$ # client.info(key=<valid key>) against the live proxy
OK info() returned: key_alias= repro-happy-path-key | spend= 0.0

Edge cases checked against the live proxy:

[SAFE] 404, valid auth + bad lookup, realistic key   -> ?REDACTED  (str + traceback)
[SAFE] 401, bad key as credential                    -> ?REDACTED  (str + traceback)
[SAFE] 64+ char key                                  -> ?REDACTED
[SAFE] orig_exception on the 401 path                -> redacted, response preserved
[SAFE] sibling list() with bad auth                  -> URL carries no raw key
[OK]   happy path, valid key lookup                  -> returns key info

Redaction stays on even when secret redaction is disabled, because the fix uses the always-on redact_string rather than the env-gated wrapper:

$ LITELLM_DISABLE_REDACT_SECRETS=true python repro.py sk-1234 sk-1a2b3c4d...
ERROR | Error getting key info: 404 Client Error: Not Found for url: http://localhost:4000/key/info?REDACTED

Type

🐛 Bug Fix

Changes

KeysManagementClient.info embeds the key in the request URL, and on failure the requests HTTPError string ("... for url: .../key/info?key=sk-...") flows to whatever logs the exception. The non-401 branch re-raised that error unchanged, and the 401 branch surfaced the same URL through UnauthorizedError(str(orig_exception)). Beyond str(e), the original error stayed attached as the chained cause/context, so logging.exception() and an uncaught error printed the key in the rendered traceback too

This redacts both branches with the always-on redact_string helper from litellm_core_utils/secret_redaction. It is deliberately the always-on helper rather than the redact_secrets wrapper, since the latter is gated by LITELLM_DISABLE_REDACT_SECRETS and a key-leak fix should not be switchable off by a log-verbosity flag. UnauthorizedError and NotFoundError now scrub their message; info() raises the wrapped errors from None so the unredacted original is not re-attached as the chain, and it hands the already-redacted string to UnauthorizedError so the retained orig_exception carries no secret. The rebuilt HTTPError keeps the original response, so callers and the CLI still read status_code and text

Only info() is touched because it is the sole client method that puts the raw key in a URL; the sibling methods (list, generate, delete) build URLs that carry a hashed key and ids rather than the plaintext secret, so they are left as is

Redaction is shape and length based (it matches ?key=<value> of 8+ chars and sk- tokens of 20+ chars), which covers real proxy keys and 64-char hashes. The /key/info route still accepts the key as a query param, so GET /key/info?key=... can land in proxy access logs and stays reachable via the preserved response object independently of this client fix; moving cross-key lookup to a header or body is a server-side change tracked in LIT-4013

Regression tests extend the mapped tests/test_litellm/proxy/client/test_keys.py; they assert the key is absent from str(exc), from orig_exception, and from the rendered traceback, and they fail on the pre-fix code while passing once the key is scrubbed to REDACTED

One residual is intentional and pinned by a test: the preserved response keeps the raw key in exc.response.request.url (and exc.request.url), so the rendered string and traceback are scrubbed but the live request URL object is not; removing the key from the URL itself is the server-side root fix tracked in LIT-4013


Note

Low Risk
Scoped client-side logging fix with no auth or server behavior changes; preserves response for structured error handling.

Overview
Prevents proxy API keys from leaking into logs when KeysManagementClient.info() fails. That method puts the lookup key in the query string; requests error text and exception chains previously echoed the full URL.

info() now runs failures through always-on redact_string, raises redacted UnauthorizedError / HTTPError with from None so the unredacted original is not chained, and keeps the original response for status/body. UnauthorizedError and NotFoundError scrub orig_exception the same way via _redact_orig_exception.

Regression tests assert the key is absent from str(exc), orig_exception, and rendered tracebacks. exc.response.request.url may still contain the key (documented residual; server-side LIT-4013).

Reviewed by Cursor Bugbot for commit 366eb06. Bugbot is set up for automated code reviews on this repo. Configure here.

@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@greptile-apps

greptile-apps Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR hardens KeysManagementClient.info() against secret exposure in error messages. The info() method embeds the lookup key as a URL query parameter; previously a non-2xx response caused requests to raise an HTTPError whose string form echoed the full URL — leaking the key to any caller that logged or propagated the exception.

  • keys.py: info() now calls redact_string on the error message before re-raising, uses from None to sever the exception chain so the unredacted original is not reachable via __cause__/__context__, and preserves response on the reconstructed error for structured access.
  • exceptions.py: Adds _redact_orig_exception and wires it into both UnauthorizedError and NotFoundError so self.orig_exception stores a redacted copy, addressing the gap surfaced in the previous review round.
  • test_keys.py: Four new regression tests assert the key is absent from str(exc), orig_exception, and the full rendered traceback on both the 404 and 401 paths; the known residual (exc.response.request.url) is explicitly pinned with a positive assertion and tracked in LIT-4013.

Confidence Score: 5/5

Safe to merge — all three changed files are scoped to the client-side error path; no auth logic, server behaviour, or database access is touched.

The fix is narrow and well-contained: it touches only the error-handling branch of a single client method, relies on an already-tested redact_string helper, and the previous review gaps (unredacted orig_exception storage and missing test assertions) are both resolved in this revision. Regression tests cover str(exc), exc.orig_exception, rendered tracebacks, and the documented residual.

No files require special attention.

Important Files Changed

Filename Overview
litellm/proxy/client/exceptions.py Adds _redact_orig_exception helper and wires it into both UnauthorizedError and NotFoundError so self.orig_exception stores a redacted copy, closing the gap flagged in the previous review round.
litellm/proxy/client/keys.py Redacts the error message before re-raising on both the 401 and non-401 paths in info(), uses from None to sever the exception chain so the original unredacted error is not reachable via __cause__/__context__, and preserves response for structured access.
tests/test_litellm/proxy/client/test_keys.py Adds four focused regression tests asserting the key is absent from str(exc), orig_exception, and the rendered traceback for both the 404 and 401 paths; also pins the documented residual (exc.response.request.url) with a positive assertion.

Reviews (5): Last reviewed commit: "fix: preserve key info unauthorized resp..." | Re-trigger Greptile

Comment thread litellm/proxy/client/exceptions.py Resolved
@greptile-apps

This comment was marked as outdated.

Comment thread litellm/proxy/client/exceptions.py Resolved
Comment thread litellm/proxy/client/keys.py Resolved
@codecov

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@yucheng-berri
yucheng-berri force-pushed the litellm_redact_client_key_leak branch from c0e94e3 to 076b454 Compare June 25, 2026 19:46
@yucheng-berri

Copy link
Copy Markdown
Contributor Author

@greptileai I addressed the orig_exception redaction gap; the exception classes now redact the retained original while preserving its response object. Please re-review

The keys management client builds GET /key/info?key=<key> and lets the
requests HTTPError propagate. str(HTTPError) renders the failing request URL
verbatim ("... for url: .../key/info?key=sk-..."), so any caller that logs the
exception leaks the full key; the 401 branch leaked the same way through
UnauthorizedError(str(orig_exception))

Redact both branches with the existing redact_secrets helper so the
secret-bearing query param is scrubbed to ?REDACTED while the status code,
reason, and response object are preserved. Server-side responses already mask
the key, so this closes the remaining client-side surface
@yucheng-berri
yucheng-berri force-pushed the litellm_redact_client_key_leak branch from 076b454 to 366eb06 Compare June 25, 2026 22:34
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Bugbot Autofix prepared a fix for the issue found in the latest run.

  • ✅ Fixed: 401 info drops response object
    • Updated info() to wrap the original HTTPError for 401 responses so UnauthorizedError keeps a redacted orig_exception with the response attached.

You can send follow-ups to the cloud agent here.

Want reviews to match your repository better? Bugbot Learning can learn team-specific rules from PR activity. A team admin can enable Learning in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 366eb06. Configure here.

Comment thread litellm/proxy/client/keys.py Outdated
if e.response.status_code == 401:
raise UnauthorizedError(e)
raise
raise UnauthorizedError(redacted_message) from None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

401 info drops response object

Medium Severity

For 401 errors in KeysManagementClient.info(), UnauthorizedError is now raised with a redacted string instead of the original HTTPError. This means code expecting to access orig_exception.response will encounter an AttributeError or lose access to the HTTP response details.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 366eb06. Configure here.

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ yucheng-berri
❌ cursoragent
You have signed the CLA already but the status is still pending? Let us recheck it.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri
mateo-berri enabled auto-merge (squash) June 26, 2026 00:35

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM; thanks!

@mateo-berri
mateo-berri merged commit 71ee1a8 into litellm_internal_staging Jun 26, 2026
74 checks passed
@mateo-berri
mateo-berri deleted the litellm_redact_client_key_leak branch June 26, 2026 00:35
yuneng-berri added a commit that referenced this pull request Jun 30, 2026
…42-31653-0629

chore(release): backport #31342, #31653 to stable/1.89.x and cut 1.89.5
yuneng-berri added a commit that referenced this pull request Jun 30, 2026
…31342_31653

chore(release): backport #31036, #31342, #31653 to stable/1.90.x and cut 1.90.1 (litellm-enterprise 0.1.43.post1)
blake-hamm added a commit to blake-hamm/bhamm-lab that referenced this pull request Jul 4, 2026
…to v1.90.3 (#257)

This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [https://github.com/BerriAI/litellm.git](https://github.com/BerriAI/litellm) | patch | `v1.90.0` → `v1.90.3` |

---

### Release Notes

<details>
<summary>BerriAI/litellm (https://github.com/BerriAI/litellm.git)</summary>

### [`v1.90.3`](https://github.com/BerriAI/litellm/releases/tag/v1.90.3)

[Compare Source](BerriAI/litellm@v1.90.2...v1.90.3)

#### Verify Docker Image Signature

All LiteLLM Docker images are signed with [cosign](https://docs.sigstore.dev/cosign/overview/). Every release is signed with the same key introduced in [commit `0112e53`](BerriAI/litellm@0112e53).

**Verify using the pinned commit hash (recommended):**

A commit hash is cryptographically immutable, so this is the strongest way to ensure you are using the original signing key:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/0112e53046018d726492c814b3644b7d376029d0/cosign.pub \
  ghcr.io/berriai/litellm:v1.90.3
```

**Verify using the release tag (convenience):**

Tags are protected in this repository and resolve to the same key. This option is easier to read but relies on tag protection rules:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/v1.90.3/cosign.pub \
  ghcr.io/berriai/litellm:v1.90.3
```

Expected output:

```
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key
```

***

#### What's Changed

- chore(release): backport [#&#8203;31923](BerriAI/litellm#31923), [#&#8203;31929](BerriAI/litellm#31929), [#&#8203;31393](BerriAI/litellm#31393) to stable/1.90.x and cut 1.90.3 by [@&#8203;mateo-berri](https://github.com/mateo-berri) in [#&#8203;32025](BerriAI/litellm#32025)

**Full Changelog**: <BerriAI/litellm@v1.90.2...v1.90.3>

### [`v1.90.2`](https://github.com/BerriAI/litellm/releases/tag/v1.90.2)

[Compare Source](BerriAI/litellm@v1.90.1...v1.90.2)

#### Verify Docker Image Signature

All LiteLLM Docker images are signed with [cosign](https://docs.sigstore.dev/cosign/overview/). Every release is signed with the same key introduced in [commit `0112e53`](BerriAI/litellm@0112e53).

**Verify using the pinned commit hash (recommended):**

A commit hash is cryptographically immutable, so this is the strongest way to ensure you are using the original signing key:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/0112e53046018d726492c814b3644b7d376029d0/cosign.pub \
  ghcr.io/berriai/litellm:v1.90.2
```

**Verify using the release tag (convenience):**

Tags are protected in this repository and resolve to the same key. This option is easier to read but relies on tag protection rules:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/v1.90.2/cosign.pub \
  ghcr.io/berriai/litellm:v1.90.2
```

Expected output:

```
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key
```

***

#### What's Changed

- chore(release): backport [#&#8203;31519](BerriAI/litellm#31519), [#&#8203;31733](BerriAI/litellm#31733) to stable/1.90.x and cut 1.90.2 by [@&#8203;yuneng-berri](https://github.com/yuneng-berri) in [#&#8203;31782](BerriAI/litellm#31782)

**Full Changelog**: <BerriAI/litellm@v1.90.1...v1.90.2>

### [`v1.90.1`](https://github.com/BerriAI/litellm/releases/tag/v1.90.1)

[Compare Source](BerriAI/litellm@v1.90.0-rc.1...v1.90.1)

#### Verify Docker Image Signature

All LiteLLM Docker images are signed with [cosign](https://docs.sigstore.dev/cosign/overview/). Every release is signed with the same key introduced in [commit `0112e53`](BerriAI/litellm@0112e53).

**Verify using the pinned commit hash (recommended):**

A commit hash is cryptographically immutable, so this is the strongest way to ensure you are using the original signing key:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/0112e53046018d726492c814b3644b7d376029d0/cosign.pub \
  ghcr.io/berriai/litellm:v1.90.1
```

**Verify using the release tag (convenience):**

Tags are protected in this repository and resolve to the same key. This option is easier to read but relies on tag protection rules:

```bash
cosign verify \
  --key https://raw.githubusercontent.com/BerriAI/litellm/v1.90.1/cosign.pub \
  ghcr.io/berriai/litellm:v1.90.1
```

Expected output:

```
The following checks were performed on each of these signatures:
  - The cosign claims were validated
  - The signatures were verified against the specified public key
```

***

#### What's Changed

- chore(release): backport [#&#8203;31036](BerriAI/litellm#31036), [#&#8203;31342](BerriAI/litellm#31342), [#&#8203;31653](BerriAI/litellm#31653) to stable/1.90.x and cut 1.90.1 (litellm-enterprise 0.1.43.post1) by [@&#8203;yuneng-berri](https://github.com/yuneng-berri) in [#&#8203;31667](BerriAI/litellm#31667)

**Full Changelog**: <BerriAI/litellm@v1.90.0...v1.90.1>

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yNDkuNSIsInVwZGF0ZWRJblZlciI6IjQzLjI0OS41IiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6WyJkZXBlbmRlbmNpZXMiXX0=-->

Co-authored-by: Renovate Bot <renovate@bhamm-lab.com>
Reviewed-on: https://codeberg.org/blake-hamm/bhamm-lab/pulls/257
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants